package com.fushenlan.epidemicControl.service.Impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fushenlan.Vo.BuildInfoVo;
import com.fushenlan.commons.ApiGlobalErrorDefinition;
import com.fushenlan.commons.GeneralResponse;
import com.fushenlan.epidemicControl.dto.BuildingInfoDto;
import com.fushenlan.epidemicControl.mapper.BuildingInfoMapper;
import com.fushenlan.epidemicControl.mapper.InhabitantInfoMapper;
import com.fushenlan.epidemicControl.service.BuildingInfoService;
import com.fushenlan.excel.ExportExcelUtil;
import com.fushenlan.po.BuildingInfo;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author XUJIN
 * @DATE 2022/4/21
 * @PACKAGE_NAME com.fushenlan.epidemicControl.service.Impl
 * @VERSION 1.0
 */
@Service
@Slf4j
public class BuildingInfoServiceImpl implements BuildingInfoService {


    /**
     * 下载楼栋模板信息
     */
    private static final String EXPORT_BUILD_FILENAME = "居委会所属楼栋信息模板";  //导出excel文件名
    private static final String EXPORT_BUILD_TITLE = "居委会下属楼栋信息表";  //导出excel标题

    /**
     * 导出楼栋信息列表excel
     */
    private static final String EXPORT_BUILD_DATA_FILENAME = "居委会下属楼栋列表一览";  //导出excel文件名

    @Autowired
    private BuildingInfoMapper buildingInfoMapper;

    @Autowired
    private InhabitantInfoMapper inhabitantInfoMapper;


    /**
     * 添加楼栋信息 注意这里涉及到房间号 楼栋与小区的级联
     * @param parentId
     * @param communityName
     * @param buildNo
     * @param roomNo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public GeneralResponse addBuildingInfo(Integer parentId,String communityName,String buildNo,String roomNo) {

        int cbd = 0;   //小区楼栋信息id
        int bbd = 0;   //单元楼栋信息id

        List<BuildingInfo> communityList  = new ArrayList<>();
        List<BuildingInfo> buildNoList  = new ArrayList<>();
        List<BuildingInfo> roomNoList  = new ArrayList<>();

        if (StringUtils.isAnyEmpty(communityName,communityName,roomNo)){
            return GeneralResponse.fail(ApiGlobalErrorDefinition.INCOMPLETE_INFO);
        }
            //先添加小区信息
            //查询该居委下面的小区是否已经存在
            BuildingInfo communityInfo = new BuildingInfo();
            communityInfo.setParentId(parentId)
                        .setLevel(1)
                        .setName(communityName);
            communityList = buildingInfoMapper.findList(communityInfo);
            if (CollectionUtil.isEmpty(communityList)){
                communityInfo .setCreateDate(new Date())
                             .setUpdateDate(new Date());
                //插入小区信息
                buildingInfoMapper.saveBuildinfo(communityInfo);
                cbd = communityInfo.getId();
            }else {  //如果该居委会已经存在该小区了
                cbd = communityList.get(0).getId();
            }

            //楼栋信息
            BuildingInfo buildNoInfo = new BuildingInfo();
            buildNoInfo.setName(buildNo)
                    .setParentId(cbd)
                    .setLevel(2);
            buildNoList = buildingInfoMapper.findList(buildNoInfo);
            //新增
            if (CollectionUtil.isEmpty(buildNoList)){
                buildNoInfo .setCreateDate(new Date())
                             .setUpdateDate(new Date());
                //插入小区信息
                buildingInfoMapper.saveBuildinfo(buildNoInfo);
                bbd = buildNoInfo.getId();
            }else {  //如果该居委会已经存在该小区了，获取其id
                bbd = buildNoList.get(0).getId();
            }

            //房间号

            BuildingInfo roomNoInfo = new BuildingInfo();
            roomNoInfo.setName(roomNo)
                        .setParentId(bbd)
                        .setLevel(3);
            roomNoList = buildingInfoMapper.findList(roomNoInfo);
            // //插入楼栋信息
            if (CollectionUtil.isEmpty(roomNoList)){
                roomNoInfo .setCreateDate(new Date())
                             .setUpdateDate(new Date());
                //插入小区信息
                buildingInfoMapper.saveBuildinfo(roomNoInfo);
            }
            return GeneralResponse.success();

    }


    /**
     * @param dto
     * @return
     */
    @Override
    public List<BuildingInfo> findBuildInfoList(BuildingInfo dto) {
        return buildingInfoMapper.findList(dto);
    }

    /**
     * 获取居委会所管辖的楼栋信息  表中涉及级联
     * @param buildingInfoDto
     * @return
     */
    @Override
    public List<BuildInfoVo> findBuildList(BuildingInfoDto buildingInfoDto) {
        List<BuildInfoVo> buildList = buildingInfoMapper.findBuildList(buildingInfoDto);
        return buildList;
    }


    /**
     * 修改楼栋表信息id
     * @param id
     * @param communityName
     * @param buildNo
     * @param roomNo
     */
    @Override
    public GeneralResponse updateBuildingInfo(Integer id, String communityName, String buildNo, String roomNo) {
        BuildingInfo buildingInfo = buildingInfoMapper.selectById(id);
        //如果房间号不为空，则更新房间号名称
        if (StringUtil.isNotEmpty(roomNo)){
            buildingInfo.setName(roomNo);
            //更新房间号
            buildingInfo.setUpdateDate(new Date());
            buildingInfoMapper.updateById(buildingInfo);

        }
        BuildingInfo bbd=  new BuildingInfo();
        if (StringUtil.isNotEmpty(buildNo)){
            //获取楼栋单元信息
             bbd = buildingInfoMapper.selectById(buildingInfo.getParentId());
            bbd.setName(buildNo);
            bbd.setUpdateDate(new Date());
            buildingInfoMapper.updateById(bbd);
        }

        if (StringUtil.isNotEmpty(communityName) && bbd != null){
            //获取小区信息
            BuildingInfo cbd = buildingInfoMapper.selectById(bbd.getParentId());
            cbd.setName(communityName);
            cbd.setUpdateDate(new Date());
            buildingInfoMapper.updateById(cbd);
        }
        return GeneralResponse.success();
    }

    /**
     * 根据楼栋id删除楼股东信息
     * @param id
     */
    @Override
    @Transactional
    public void deleteBuildinginfo(Integer id) {
       //删除楼栋信息，删除level = 3即房间号
        QueryWrapper<BuildingInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id).eq("level",3);
        buildingInfoMapper.delete(wrapper);
    }


    /**
     * 下载楼栋信息导入模板
     * @param list
     * @param response
     */
    @Override
    public void downloadBuildModel(List<?> list, HttpServletResponse response) {
        // 导出数据，数据，数据类型，文件名称，表名，响应对象
        ExportExcelUtil.exportExcel(list,BuildInfoVo.class,EXPORT_BUILD_FILENAME,EXPORT_BUILD_TITLE,response);
    }


    /**
     * 导出该居委会所有的楼栋信息列表
     * @param neighborId
     * @param response
     */
    @Override
    public void exportBuildInfo(Integer neighborId, HttpServletResponse response) {
        BuildingInfoDto buildingInfoDto = new BuildingInfoDto();
        buildingInfoDto.setParentId(neighborId);
        List<BuildInfoVo> buildList = buildingInfoMapper.findBuildList(buildingInfoDto);
        ExportExcelUtil.exportExcel(buildList,BuildInfoVo.class,EXPORT_BUILD_DATA_FILENAME,EXPORT_BUILD_TITLE,response);
    }


    /**
     * 上传楼栋信息列表
     * @param neighborId
     * @param multipartFile
     * @param response
     * @return
     */
    @Override
    public void uploadBuildList(Integer neighborId, MultipartFile multipartFile,HttpServletResponse response) throws Exception {

            //暂时模拟读取本地文件test
            //FileInputStream inputStream = new FileInputStream(new File("D:\\项目\\居委会下属楼栋列表一览-20220427.xls"));
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            //解析导入列表
            List<BuildInfoVo> buildInfoVos = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                    BuildInfoVo.class, params);
            int count = 0; //初始化导入成功数量
            for (BuildInfoVo tmp : buildInfoVos){
                if (StringUtils.isAnyEmpty(tmp.getCommunityName(),tmp.getBuildNo(),tmp.getRoomNo())){
                    continue;
                }
                GeneralResponse generalResponse = addBuildingInfo(neighborId, tmp.getCommunityName(), tmp.getBuildNo(), tmp.getRoomNo());
                if (generalResponse.getCode().equals(GeneralResponse.CODE_SUCCESS)){
                    count++;
                }
            }
            log.info("上传楼栋信息excel列表成功，excel总数为{}条，成功{}条",buildInfoVos.size(),count);
    }

    public static void main(String[] args) throws Exception {
        new BuildingInfoServiceImpl().uploadBuildList(2,null,null);
    }

}
